<template>
  <div class="inbound-container">
    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 操作栏 -->
      <div class="action-bar">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索入库记录"
            clearable
            style="width: 300px"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="openDialog('create')">
          <el-icon>
            <Plus/>
          </el-icon>
          新建入库
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="paginatedData" border stripe>
        <el-table-column prop="docNumber" label="单据号" width="220" align="center"/>
        <el-table-column prop="productName" label="商品名称" width="180" align="center">
          <template #default="{ row }">
            {{ productMap[row.productId] || '未知商品' }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" align="center"/>
        <el-table-column prop="supplierName" label="供货商" width="200" align="center">
          <template #default="{ row }">
            {{ supplierMap[row.supplierId] || '未知商品' }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="100" align="center"/>
        <el-table-column prop="type" label="入库方式" width="160" align="center"/>
        <el-table-column prop="inboundTime" label="入库时间" width="200" align="center"/>

        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDialog('edit', row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="filteredData.length"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 入库弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'create' ? '新建入库' : '编辑入库'"
        width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="商品名称" prop="productId">
          <el-select
              v-model="form.productId"
              placeholder="选择商品"
              filterable
              style="width: 100%"
          >
            <el-option
                v-for="product in products"
                :key="product.id"
                :label="product.name"
                :value="product.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="数量" prop="quantity">
          <el-input-number
              v-model="form.quantity"
              :min="1"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="供货商" prop="supplierId">
          <el-select
              v-model="form.supplierId"
              placeholder="选择供货商"
              filterable
              style="width: 100%"
          >
            <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库方式" prop="type">
          <el-select
              v-model="form.type"
              placeholder="选择入库方式"
              filterable
              style="width: 100%"
          >
            <el-option
                label="正常入库"
                value="正常入库"
            />
            <el-option
                label="调拨入库"
                value="调拨入库"
            />
            <el-option
                label="客退入库"
                value="客退入库"
            />
            <el-option
                label="盲入库"
                value="盲入库"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="入库时间" prop="inboundTime">
          <el-date-picker
              v-model="form.inboundTime"
              type="datetime"
              placeholder="选择日期"
              value-format="YYYY-MM-DD hh:mm:ss"
          />
        </el-form-item>


      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search, Plus} from '@element-plus/icons-vue'
import {
  addInbound,
  deleteInboundById,
  getAllInbound,
  getAllProducts,
  getAllSuppliersInfo,
  updateInbound
} from "@/api/auth.js";

// 模拟商品数据
const products = ref([
  {id: 1, name: '笔记本电脑'},
  {id: 2, name: '手机'},
  {id: 3, name: '显示器'},
  {id: 4, name: '鼠标'},
  {id: 5, name: '键盘'}
])
const suppliers = ref([
  {id: 1, name: '供应商A'},
  {id: 2, name: '供应商B'},
  {id: 3, name: '供应商C'},
  {id: 4, name: '供应商D'},
  {id: 5, name: '供应商E'}
])

// 商品名称映射
const productMap = computed(() =>
    products.value.reduce((map, item) => {
      map[item.id] = item.name
      return map
    }, {})
)
const supplierMap = computed(() =>
    suppliers.value.reduce((map, item) => {
      map[item.id] = item.name
      return map
    }, {})
)

// 模拟入库数据（完全匹配截图）
const rawData = ref([
  {
    id: 1,
    docNumber: 'IN2023000',
    productId: 1,
    quantity: 94,
    operator: '张三',
    type:'正常入库',
    inboundTime: '2023-01-01',
    supplierId: 4,

  },
  {
    id: 2,
    docNumber: 'IN2023001',
    productId: 2,
    quantity: 51,
    type:'正常入库',
    operator: '李四',
    inboundTime: '2023-02-02',
    supplierId: 1,
  },
  {
    id: 3,
    docNumber: 'IN2023002',
    productId: 3,
    type:'正常入库',
    quantity: 110,
    operator: '王五',
    inboundTime: '2023-03-03',
    supplierId: 2,
  },
  {
    id: 4,
    docNumber: 'IN2023004',
    productId: 4,
    quantity: 45,
    type:'正常入库',
    operator: '李四',
    inboundTime: '2023-05-05',
    supplierId: 3,
  }
])
const initData = async () => {
  try {
    const res = await getAllInbound()
    if (res.code === 200) {
      rawData.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }
  try {
    const res = await getAllProducts()
    if (res.code === 200) {
      products.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }
  try {
    const res = await getAllSuppliersInfo()
    if (res.code === 200) {
      suppliers.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }


}
onMounted(() => {
  initData()
})
// 分页配置
const pagination = reactive({
  current: 1,
  size: 10
})

// 搜索逻辑
const searchKeyword = ref('')
const filteredData = computed(() => {
  return rawData.value.filter(item =>
      item.docNumber.includes(searchKeyword.value) ||
      productMap.value[item.productId]?.includes(searchKeyword.value) ||
      item.operator.includes(searchKeyword.value)
  )
})

// 分页数据
const paginatedData = computed(() => {
  const start = (pagination.current - 1) * pagination.size
  return filteredData.value.slice(start, start + pagination.size)
})

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref()
const form = reactive({
  supplierId: null,
  docNumber: '',
  productId: null,
  quantity: 1,
  inboundTime: '',
  type:''
})

// 验证规则
const rules = {
  productId: [{required: true, message: '请选择商品', trigger: 'change'}],
  quantity: [{required: true, message: '请输入数量', trigger: 'blur'}],
  operator: [{required: true, message: '请选择操作人', trigger: 'change'}],
  inboundTime: [{required: true, message: '请选择日期', trigger: 'change'}]
}

// 打开弹窗
const openDialog = (type, row) => {
  dialogType.value = type
  if (type === 'edit' && row) {
    Object.assign(form, row)
  } else {
    form.docNumber = `IN2023${String(rawData.value.length + 1).padStart(3, '0')}`
    form.productId = null
    form.quantity = 1
    form.inboundTime = ''
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {

  try {

    if (dialogType.value === 'create') {
      console.log(form)
      try {
        const res = await addInbound(form)
        if (res.code === 200) {
          ElMessage.success('添加成功!')
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        ElMessage.error(e)
      }


    } else {
      try {
        const res = await updateInbound(form)
        if (res.code === 200) {
          ElMessage.success('修改成功')
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        ElMessage.error(e)
      }

    }


    dialogVisible.value = false
    await initData()
  } catch (error) {
    ElMessage.warning('请完善表单信息')
  }
}

// 删除操作
const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确定删除单据 ${row.docNumber} 吗？`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  try {
    const res = await deleteInboundById(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error(e)
  }
  await initData()
}
</script>

<style scoped>
.inbound-container {
  padding: 20px;
  background: #fff;
}

.action-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 10px;
  --el-table-border-color: #ebeef5;
}

:deep(.el-dialog) .el-form-item__label {
  font-weight: 500;
}
</style>